package cn.zh.stan.activity;


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import cn.zh.stan.BaseUrl;
import cn.zh.stan.ITem.UserItem;
import cn.zh.stan.MyApplication;
import cn.zh.stan.R;
import cn.zh.stan.fragment.MineFragment;
import cn.zh.stan.util.PicassoImageLoader;
import cn.zh.stan.util.RegexUtils;
import cn.zh.stan.util.RoundImageView;
import cn.zh.stan.util.ToastUtil;
import it.sephiroth.android.library.picasso.Picasso;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class UserEdit extends BaseActivity {
    ImageView min_back;
    ArrayList<ImageItem> images = null;
    LinearLayout pholin;
    PopupWindow popupWindow;
    public static final int REQUEST_CODE_SELECT = 100;
    RoundImageView hphoto;
    File file;

    MyApplication mapp;
    SharedPreferences sp;
    String uid;

    EditText uname,uphone,email;

    LinearLayout sexlin,birlin;
    TextView sex,birth;
    Button msave;
    String sextype="0";
    ArrayList<String> sexs=new ArrayList<String>();
    String[] sts={"保密","男","女"};

    String headurl="";
    UserItem userItem=null;
    Bitmap bm;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                hphoto.setImageBitmap(bm);
                break;
            }
        }
     };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_edit);
        mapp= (MyApplication) getApplication();
        sp=mapp.getSp();
        uid=sp.getString("uid","2");
        userItem=mapp.getUserItem();
        initv();

        }



    public void initv(){
        inimgpacker();
        min_back= (ImageView) findViewById(R.id.min_back);
        pholin= (LinearLayout) findViewById(R.id.pholin);
        hphoto= (RoundImageView) findViewById(R.id.hphoto);
        uname= (EditText) findViewById(R.id.uname);
        uphone= (EditText) findViewById(R.id.uphone);
        email= (EditText) findViewById(R.id.email);
        sexlin= (LinearLayout) findViewById(R.id.sexlin);
        birlin= (LinearLayout) findViewById(R.id.birlin);
        sex= (TextView) findViewById(R.id.sex);
        birth= (TextView) findViewById(R.id.birth);
        msave= (Button) findViewById(R.id.msave);

        min_back.setOnClickListener(this);
        pholin.setOnClickListener(this);

        sexlin.setOnClickListener(this);
        birlin.setOnClickListener(this);
        msave.setOnClickListener(this);
        sexs.clear();
       for (int i=0;i<sts.length;i++){
           sexs.add(sts[i]);
          }
        // hphoto.setImageDrawable(bm);
        if (null==userItem){
            return;
        }
        System.out.println("-------------->用户头像===="+userItem.getIndexPic());

        uname.setText(userItem.getTrueName());
        birth.setText(userItem.getBirthday());
        email.setText(userItem.getEmail());
        uphone.setText(userItem.getPhone());
        switch (userItem.getGender()){
            case "0":
                sex.setText("保密");
                break;
            case "1":
                sex.setText("男");
                break;
            case "2":
                sex.setText("女");
                break;
           }

        new Thread(new Runnable() {
            @Override
            public void run() {
                bm = getImageBitmap(userItem.getIndexPic());

            }
        }).start();

        }




    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id=view.getId();
        switch (id){
            case R.id.min_back:
               if (headurl.equals("")){
                }else {
                   mapp.setHeadurl(headurl);
               }
                finish();
                break;
            case R.id.pholin:
                getPOp();
                break;
            case R.id.photo:
                Intent intent1 = new Intent(this, ImageGridActivity.class);
                intent1.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,true); // 是否是直接打开相机
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                popupWindow.dismiss();
                break;
            case R.id.album:
                Intent intent2 = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent2, REQUEST_CODE_SELECT);
                popupWindow.dismiss();
                break;
            case R.id.cancle:
                popupWindow.dismiss();
                break;
            case R.id.sexlin:
                //性别选择
                getsex();
                break;
            case R.id.birlin:
                //生日选择
                getBir();
                break;
            case R.id.msave:
                EditUser();
                break;
               }
              }


    public void inimgpacker(){
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);  //显示拍照按钮
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
        }


    public void getPOp(){
        View view1= LayoutInflater.from(UserEdit.this).inflate(R.layout.ph_layout,null,false);
        LinearLayout photo=view1.findViewById(R.id.photo);
        LinearLayout album=view1.findViewById(R.id.album);
        LinearLayout cancle=view1.findViewById(R.id.cancle);
        photo.setOnClickListener(this);
        album.setOnClickListener(this);
        cancle.setOnClickListener(this);
        popupWindow = new PopupWindow(view1, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.GRAY));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setAnimationStyle(R.style.popwinstyle);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha=0.5f;
        getWindow().setAttributes(lp);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha=1.0f;
                getWindow().setAttributes(lp);

             }
        });
        popupWindow.showAtLocation(findViewById(R.id.activity_user_edit), Gravity.BOTTOM, 0, 0);
        }





    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    headurl=images.get(0).path;
                    Bitmap bm= BitmapFactory.decodeFile(images.get(0).path);
                    hphoto.setImageBitmap(bm);
                    file=new File(images.get(0).path);

//                    file = CompressHelper.getDefault(this).compressToFile(ofile);
                    senPho();

                }
             }
           }
        }







      public void senPho(){
         OkHttpUtils.post(BaseUrl.mem_photo)
                 .params("userId",uid)
                 .params("isThumb","0")
                 .params("stlWidthStr","")
                 .params("file",file)
                 .execute(new StringCallback() {
                     @Override
                     public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                         System.out.println("---------->上传头像===="+s);
                         try {
                             JSONObject js=new JSONObject(s);
                             boolean State=js.getBoolean("State");
                             if (State){
                              boolean Flag=js.getBoolean("Flag");
                              String Msg=js.getString("Msg");
                              ToastUtil.showShort(UserEdit.this,Msg);
                             }
                         } catch (JSONException e) {
                             e.printStackTrace();
                         }
                     }
                     @Override
                     public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                         super.onError(isFromCache, call, response, e);
                     }
                 });
                }
                 //编辑会员资料
                public void EditUser(){
                String truena=uname.getText().toString();
                String birthday=birth.getText().toString();
                String emai=email.getText().toString();
                final String phone=uphone.getText().toString();

                OkHttpUtils.post(BaseUrl.men_edit)
                        .params("userId",uid)
                        .params("truename",truena)
                        .params("gender",sextype)
                        .params("birthday",birthday)
                        .params("email",emai)
                        .params("phone",phone)
                        .execute(new StringCallback() {
                            @Override
                            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                                System.out.println("------------->用户修改资料==="+s);
                                try {
                                    JSONObject js=new JSONObject(s);
                                    boolean State=js.getBoolean("State");
                                    if (State){
                                      boolean Flag=js.getBoolean("Flag");
                                      if (Flag){
                                          mapp.setHeadurl(headurl);
                                          if (RegexUtils.checkMobile(phone)){
                                          SharedPreferences.Editor editor=mapp.getSp().edit();
                                          editor.putString("phone",phone);
                                          editor.commit();
                                          }
                                          finish();
                                      }
                                     String Msg=js.getString("Msg");
                                     ToastUtil.showShort(UserEdit.this,Msg);

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                            @Override
                            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                                super.onError(isFromCache, call, response, e);
                            }
                        });
                    }

            public void getUinfo(){
                    OkHttpUtils.get(BaseUrl.men_getinfo)
                    .params("userId",uid)
                    .execute(new StringCallback() {
                        @Override
                        public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                            System.out.println("----------->获取用户资料==="+s);
                            try {
                                JSONObject js = new JSONObject(s);
                                boolean State=js.getBoolean("State");
                                if (State){
                                JSONObject Res=js.getJSONObject("Res");

                                    String  Id=Res.getString("Id");
                                    String MemberId=Res.getString("MemberId");
                                    String TrueName=Res.getString("TrueName");
                                    String Gender=Res.getString("Gender");
                                    String  Birthday=Res.getString("Birthday");
                                    String  Email=Res.getString("Email");
                                    String  Phone=Res.getString("Phone");
                                    String  IndexPic=Res.getString("IndexPic");
                                    String  CreateTime=Res.getString("CreateTime");
                                    String  IdCard1=Res.getString("IdCard1");
                                    String  IdCard2=Res.getString("IdCard2");
                                    String  Photo=Res.getString("Photo");
                                    String  Status=Res.getString("Status");
                                    UserItem userItem=new UserItem( Id,  MemberId,  TrueName,  Gender,  Birthday,  Email,  Phone,  IndexPic,  CreateTime,  IdCard1,  IdCard2, Photo, Status);
                                   // Drawable bm=loadImageFromNetwork("http://120.26.41.167:8092/api"+IndexPic);
                                    String url="http://120.26.41.167:8092"+IndexPic;
                                   Picasso.with(UserEdit.this).load(url).error(R.mipmap.avatar).into(hphoto);
                                    // hphoto.setImageDrawable(bm);
                                    uname.setText(TrueName);
                                    birth.setText(Birthday);
                                    email.setText(Email);
                                    uphone.setText(Phone);
                                    switch (Gender){
                                        case "0":
                                            sex.setText("保密");
                                            break;
                                        case "1":
                                            sex.setText("男");
                                            break;
                                        case "2":
                                            sex.setText("女");
                                            break;
                                     }
                                  }
                              } catch (JSONException e) {
                                e.printStackTrace();
                            }
                         }
                        @Override
                        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                            super.onError(isFromCache, call, response, e);
                        }
                    });
               }



    public void getsex(){
        OptionsPickerView pvOptions = new  OptionsPickerView.Builder(UserEdit.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                //返回的分别是三个级别的选中位置
                String s =  sexs.get(options1);
                sex.setText(s);
                sextype=options1+"";
                 }
              })
//                        .setSubmitText("确定")//确定按钮文字
//                        .setCancelText("取消")//取消按钮文字
//                        .setTitleText("城市选择")//标题
                .setSubCalSize(20)//确定和取消文字大小
//                        .setTitleSize(20)//标题文字大小
//                        .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLACK)//确定按钮文字颜色
                .setCancelColor(Color.BLACK)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF333333)//标题背景颜色 Night mode
//                        .setBgColor(0xFF000000)//滚轮背景颜色 Night mode
                       .setContentTextSize(20)//滚轮文字大小
//                        .setTextColorCenter(Color.BLUE)//设置选中项的颜色
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
//                        .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
//                        .setLinkage(false)//设置是否联动，默认true
//                        .setLabels("省", "市", "区")//设置选择的三级单位
//                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .setCyclic(false, false, false)//循环与否
//                        .setSelectOptions(1, 1, 1)  //设置默认选中项
//                        .setOutSideCancelable(false)//点击外部dismiss default true
//                        .isDialog(true)//是否显示为对话框样式
                .build();
           pvOptions.setPicker(sexs);
           pvOptions.show();
           }



      public void getBir(){
          TimePickerView pvTime = new TimePickerView.Builder(UserEdit.this, new TimePickerView.OnTimeSelectListener() {
              @Override
              public void onTimeSelect(Date date2, View v) {//选中事件回调
                  String time = getTime(date2);
                  birth.setText(time);
                   }
          })
                  .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                  .setCancelText("取消")//取消按钮文字
                  .setSubmitText("确定")//确认按钮文字
                  .setContentSize(20)//滚轮文字大小
                  .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                  .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                  .isCyclic(true)//是否循环滚动
                  .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                  .setTitleColor(Color.BLACK)//标题文字颜色
                  .setSubmitColor(Color.BLACK)//确定按钮文字颜色
                  .setCancelColor(Color.BLACK)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                  .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                  .build();
          pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
          pvTime.show();
          }



    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
        }



    public Bitmap getImageBitmap(String url) {
        URL imgUrl = null;
        Bitmap bitmap = null;
        try {
            imgUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imgUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
          handler.sendEmptyMessage(0);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}



